﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Sockets;
using System.Text;
using System.Threading.Tasks;

namespace NFine.Code
{
    public class MySocket
    {
        public int port { get; set; }
        public string host { get; set; }
        public MySocket(int port, string host)
        {
            this.port = port;
            this.host = host;
        }
        public MySocket()
        {
        }
        public string SendMessage(string xml)
        {
            IPAddress ip = IPAddress.Parse(host);
            IPEndPoint ipe = new IPEndPoint(ip, port);

            Socket clientSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
            clientSocket.Connect(ipe);

            //send message
            string sendStr = xml;
            byte[] sendBytes = Encoding.ASCII.GetBytes(sendStr);
            clientSocket.Send(sendBytes);

            //receive message
            string recStr = "";
            byte[] recBytes = new byte[10240];
            int bytes = clientSocket.Receive(recBytes, recBytes.Length, 0);
            recStr += Encoding.UTF8.GetString(recBytes, 0, bytes);
            clientSocket.Close();
            return recStr;
        }
    }
}
